import logic
from dao import BlackListSDK,SendHistorySDK
scraper = logic.JobScraper()
class Controller:
    # 导入UI类后，替换以下的 object 类型，将获得 IDE 属性提示功能
    ui: object
    def __init__(self):
        pass
    def init(self, ui):
        """
        得到UI实例，对组件进行初始化配置
        """
        self.ui = ui
        self.update_black_list_table()
        self.update_send_history_table()
        # 绑定标签页切换事件

    def on_tab_changed(self, event):
        """处理标签页切换事件"""
        current_tab = self.ui.tk_tabs_page.select()
        tab_text = self.ui.tk_tabs_page.tab(current_tab, 'text')
        if tab_text == '黑名单':
            self.update_black_list_table()
        elif tab_text == '投递记录':
            self.update_send_history_table()

    def update_send_history_table(self):
        """更新投递记录表格"""
        # 清空表格
        for item in self.ui.tk_table_send_history.get_children():
            self.ui.tk_table_send_history.delete(item)
        # 获取并添加数据
        records = SendHistorySDK.list_records()
        for record in records:
            self.ui.tk_table_send_history.insert('', 'end', values=record)

    def update_black_list_table(self):
        """更新黑名单表格"""
        self.black_list = BlackListSDK.list_companies()
        # 清空表格
        for item in self.ui.tk_table_black_list.get_children():
            self.ui.tk_table_black_list.delete(item)
        # 添加数据
        for company in self.black_list:
            self.ui.tk_table_black_list.insert('', 'end', values=company)

    def add_black(self, evt):
        """添加黑名单企业"""
        name = self.ui.tk_input_black_company.get()
        if name.strip():
            BlackListSDK.add_company(name)
            self.update_black_list_table()
            self.ui.tk_input_black_company.delete(0, 'end')
            scraper.refresh_black_list()

    def delete_black(self, evt):
        """删除黑名单企业"""
        selection = self.ui.tk_table_black_list.selection()
        if selection:
            item = self.ui.tk_table_black_list.item(selection[0])
            company_name = item['values'][1]  # 获取公司名称
            BlackListSDK.remove_company(company_name)
            scraper.refresh_black_list()


    def login(self,evt):
        scraper.launch_browser()
        scraper.login_page()

    def start_send(self,evt):
        num = int(self.ui.tk_input_send_num.get())
        url = self.ui.tk_input_send_url.get()
        scraper.set_url(url)
        scraper.scrape_jobs(num)
